<template>
  <Dialog
    v-model="dialogVisible"
    width="800px"
    :title="typeIndex === 'add' ? t('staff.add') : t('staff.edit')"
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
    maxHeight="680px"
  >
    <el-form :model="form" ref="formRef" label-width="110px">
      <el-form-item :label="t('manualBook.title')" prop="title" required>
        <el-input v-model="form.title" />
      </el-form-item>

      <!-- 修改点1：增加状态区分和错误提示 -->
      <el-form-item :label="t('manualBook.file_url')" prop="file_id">
        <UploadFile
          class="w-100%"
          url="/common/uploadFile"
          :fileSize="1024"
          drag
          :file-type="['pdf']"
          :params="{ directory: 17, is_mark: 1 }"
          :limit="1"
          :fileListMap="picList.filter((file) => file.status === 'success')"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadCallback"
          @upload-error="handleUploadError"
          @handle-remove-file="handleRemoveFile"
          @handle-picture-card-preview="handlePictureCardPreview"
        />
        <!-- 显示真实错误信息 -->
        <div v-if="uploadError" class="el-upload__tip el-upload__tip--error">
          {{ t('manualBook.uploadFailedTip') }}
        </div>
        <!-- 新增：文件大小提示 -->
        <div class="el-upload__tip"> 最大支持上传 {{ maxFileSizeMB }}MB 的文件 </div>
      </el-form-item>

      <el-form-item :label="t('article.pids')" class="w-95%" prop="pids" required>
        <el-input v-model="productDisplayText" disabled :placeholder="'请选择' + t('article.pids')">
          <template #append>
            <el-button size="small" type="primary" @click="handleOpenMining">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('common.save') }}</el-button>
    </template>
    <DialogProduct
      ref="DialogProductRef"
      @expose-multiple-data="getExposeProductData"
      :multiple="true"
      :pagination="false"
    />
  </Dialog>
</template>

<script setup lang="ts">
import { createImageViewer } from '@/components/ImageViewer'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import DialogProduct from '@/components/Dialog/src/Product.vue'
import { editInfoApi, createDataApi } from '@/api/manualBook'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

// 新增：文件大小限制配置
const maxFileSize = 1024 * 1024 * 1024 // 1GB（单位：字节）
const maxFileSizeMB = Math.round(maxFileSize / (1024 * 1024)) // 转换为MB

const dialogVisible = ref<boolean>(false)
const typeIndex = ref<string>()
const currencyList = ref<Array<Record<string, any>>>([])
const showList = ref<Array<Record<string, any>>>([])
const productDisplayText = ref('')
// 修改点2：加强错误状态管理
const uploadError = ref<string>('')
const getDropDownBoxInfo = async () => {}
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  file_id: '',
  title: '',
  pids: '',
  type: 1
})

const DialogProductRef = ref<any>(null)

const handleOpenMining = () => {
  nextTick(() => {
    DialogProductRef!.value!.dialogVisible = true
    const selectedProducts = form.value.pids
      ? form.value.pids.split(',').map((id: string) => ({ id: parseInt(id.trim()) }))
      : []
    DialogProductRef!.value!.initialize(selectedProducts)
  })
}

const getExposeProductData = (val: any) => {
  form.value.pids = val.map((item: any) => item.id).join(',')
  productDisplayText.value = val.map((item: any) => item.cname).join(',')
}

const picList = ref<any[]>([])
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 修改点3：严格检查文件状态
        if (!fileObj.value || fileObj.value.status !== 'success') {
          ElMessage.error(t('manualBook.uploadFailedTip'))
          return
        }

        form.value.file_id = String(fileObj.value.id)

        const resp =
          typeIndex.value === 'add'
            ? await createDataApi(form.value)
            : await editInfoApi(form.value)

        if (resp && resp.code === 0) {
          ElMessage.success(
            typeIndex.value === 'add'
              ? t('manualBook.createSuccess')
              : t('manualBook.updateSuccess')
          )
          closeDialog(formEl)
          emit('refresh')
        }
      } catch (error) {
        console.error('提交失败', error)
      }
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    file_id: '',
    title: '',
    pids: ''
  }
  // 修改点4：重置所有上传状态
  uploadError.value = ''
  picList.value = []
  fileObj.value = null
  productDisplayText.value = ''
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = (type: string, row?: Record<string, any>) => {
  typeIndex.value = type
  picList.value = []
  uploadError.value = ''
  getDropDownBoxInfo()
  fileObj.value = null
  if (type === 'edit') {
    form.value = row!
    if (form.value.file_id) {
      // 修改点5：标记为成功状态
      picList.value = [
        {
          name: form.value.file_name,
          id: form.value.file_id,
          url: form.value.file_url,
          status: 'success' // 关键修改：明确状态
        }
      ]
      fileObj.value = {
        name: form.value.file_name,
        id: form.value.file_id,
        url: form.value.file_url,
        status: 'success'
      }
    }
    if (form.value.product_list) {
      productDisplayText.value = form.value.product_list
    }
  }
}

defineExpose({
  dialogVisible,
  getBackShow
})

const fileObj = ref<any>(null)
const handleUploadCallback = (val: any) => {
  // 修改点6：上传成功时明确标记状态
  const fileData = { ...val, status: 'success' }
  picList.value = [fileData] // 只保留成功文件
  fileObj.value = fileData
  uploadError.value = ''
}

// 修改点7：完整错误处理逻辑
const handleUploadError = (error: any, file: File) => {
  console.error('文件上传失败:', error, file)
  // 新增：文件大小错误判断
  uploadError.value = t('manualBook.uploadFailedTip')
  // 立即清除失败文件
  picList.value = []
  fileObj.value = null
}

const handleRemoveFile = (val: any) => {
  picList.value = []
  fileObj.value = null
  uploadError.value = ''
}

const handlePictureCardPreview = (url: any) => {
  try {
    if (!url) return
    if (url.toLowerCase().endsWith('.pdf')) {
      window.open(url, '_blank')
      return
    }

    if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
      return createImageViewer({
        urlList: [url]
      })
    window.open(url)
  } catch (error) {
    console.error('预览失败:', error)
  }
}
</script>

<style lang="less" scoped>
.m-r-4 {
  margin-right: 16px;
}

.el-upload__tip--error {
  margin-top: 7px;
  font-size: 12px;
  color: #f56c6c;
}

/* 新增：文件大小提示样式 */
.el-upload__tip {
  margin-top: 7px;
  font-size: 12px;
  color: #909399;
}
</style>
